//
//  MemoViewerController.m
//  MokoAPP
//
//  Created by 현식 강 on 11. 8. 20..
//  Copyright 2011 아이온. All rights reserved.
//

#import "MemoViewerController.h"
#import "MemoWriteViewController.h"
#import "MokoAppDelegate.h"
#import "HTMLParser.h"
#import "ScrollingLabel.h"
#import "MemoRootViewController.h"
#import "MemoListTableViewController.h"
#import "ParsingDirector.h"
#import "MemoArticleVO.h"
#import <QuartzCore/QuartzCore.h>
@implementation MemoViewerController
@synthesize replyable, articleId, addr, userName, date, titleText, userId;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [vo release];
    [addr release];
    [articleId release];
    [userName release];
    [date release];
    [titleText release];
    [userId release];
    [nameTextField release];
    [contentTextView release];
    [deleteButton release];
    [fromOrToLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    contentTextView.layer.cornerRadius = 7;
    contentTextView.clipsToBounds = YES;
    
    // 백버튼 커스터마이징
    // backBarButtonItem 이었나 암튼 이거로는 커스텀뷰가 안돼서 이렇게 지정
    UIImage* image = [UIImage imageNamed:@"back_left_button.png"];
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backStep) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, image.size.width/2, image.size.height/2);
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = item;
    [item release];

    // Do any additional setup after loading the view from its nib.
}
-(void) backStep {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) viewWillAppear:(BOOL)animated {
    if( viewWillAppearCalled == NO )  {
        // Fake right button to align titleView properly.
        UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 1)] autorelease]];
        // Width equivalent to system default Done button's (which appears on pushed view in my case).
        rightBarButtonItem.enabled = NO;
        self.navigationItem.rightBarButtonItem = rightBarButtonItem;
        [rightBarButtonItem release];
        nameTextField.text = userName;
        ScrollingLabel* label = [[ScrollingLabel alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
        label.text = titleText;
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor whiteColor];
        UIView* titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width - 60, [[UIScreen mainScreen] bounds].size.height)];
        titleView.clipsToBounds = YES;
        [titleView addSubview:label];
        self.navigationItem.titleView = titleView;
        CGRect titleframe = [self.navigationItem.titleView frame];
        CGSize labelSize = [titleText sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:titleframe.size];
        titleframe.size = labelSize;
        self.navigationItem.titleView.frame = titleframe;
        label.font = [UIFont fontWithName:@"Helvetica" size:17.0];
        [label sizeToFit];
        CGRect frame = label.frame;
        frame.size.width = [[UIScreen mainScreen] bounds].size.width - 80;
        self.navigationItem.titleView.frame = frame;
        float labelX = (self.navigationItem.titleView.frame.size.width - label.frame.size.width) / 2;
        frame = label.frame;
        frame.origin.x = labelX;
        label.frame = frame;
        if( label.frame.size.width > self.navigationItem.titleView.frame.size.width )
            [label startScrolling];
        [titleView release];
        
        [label release];
        contentTextView.text = @"";
        fromOrToLabel.text = @"";
        GET_APPDELEGATE;
    
        [delegate.httpClient requestURL:addr httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(viewFinished:)];
    }
    viewWillAppearCalled = YES;
}
-(void)viewFinished:(NSData*)data {
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    vo = [[director getMemoArticle] retain];
    if( vo.login == YES ) {
        if( vo.replyable == YES ) {
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(reply)];
            self.navigationItem.rightBarButtonItem = item;
            [item release];
            self.userId = vo.userId;
            fromOrToLabel.text = @"FROM : ";
        } else {
            fromOrToLabel.text = @"TO : ";
        }
        contentTextView.text = vo.content;
    } else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"로그인이 필요합니다" message:@"로그인한 유저만 쪽지를 확인할 수 있습니다.\n로그인 하시겠습니까?" delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
        [alert show];
        alert.tag = 1;
        [alert release];
    }
    viewWillAppearCalled = NO;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( alertView.tag == 1 ) {
        if( buttonIndex == 0 )
            [self.navigationController popViewControllerAnimated:YES];
        else {
            GET_APPDELEGATE;
            [self presentModalViewController:delegate.loginViewController animated:YES];
        }
    }
}
- (void)viewDidUnload
{
    [userId release];
    [contentTextView release];
    contentTextView = nil;
    [deleteButton release];
    deleteButton = nil;
    [fromOrToLabel release];
    fromOrToLabel = nil;
    [nameTextField release];
    nameTextField = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)finishLoading:(NSData*) data {
    NSArray* controllers = [self.navigationController viewControllers];
    MemoRootViewController* memo = [controllers objectAtIndex:[controllers count] - 2];
    [memo firstList];
    [self backStep];
}
-(void)reply {
    MemoWriteViewController* memoViewController;
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
        memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController" bundle:nil];
    else
        memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController-iPad" bundle:nil];
    memoViewController.toUserId = userId;
    memoViewController.toUserName = userName;
    
    [self presentModalViewController:memoViewController animated:YES];
}
- (IBAction)deleteMemo:(id)sender {
    GET_APPDELEGATE;
    [delegate.httpClient requestURL:[addr stringByReplacingOccurrencesOfString:@"exec=view" withString:@"exec=del"] httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}
@end
